package com.stox.services.core.subscription;

import java.util.HashSet;
import java.util.Set;
import java.util.TimerTask;

import com.stox.services.data.provider.manager.BarManager;
import com.stox.shared.core.model.Bar;
import com.stox.shared.core.model.enumeration.BarSpan;
import com.stox.shared.core.model.intf.Callback;
import com.stox.shared.core.util.Constant;
import com.stox.shared.core.util.converter.BarConverter;

public class BarPublisher extends TimerTask implements Callback<String, Boolean> {
	
	public static final BarPublisher INSTANCE = new BarPublisher();
	
	private final Set<Long> scripIds = new HashSet<>();
	
	private BarPublisher() {
		Constant.timer.schedule(this, 1000, 1000);
	}
	
	@Override
	public void run() {
		for(Long scripId : scripIds){
			Bar bar = BarManager.INSTANCE.getLast(scripId, BarSpan.DAILY);
			if(null != bar){
				SubscriptionManager.INSTANCE.sendMessage(BarConverter.INSTANCE.encode(bar));
			}
		}
	}

	@Override
	public Boolean execute(String message) {
		if(BarConverter.INSTANCE.supports(message)){
			String[] tokens = message.split(","); 
			Long scripId = Long.parseLong(tokens[1]);
			Boolean subscribe = Boolean.valueOf(tokens[2]);
			if(subscribe){
				scripIds.add(scripId);
			}else{
				scripIds.remove(scripId);
			}
			return Boolean.TRUE;
		}
		return Boolean.FALSE;
	}
}
